/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.dusa.switco;

import net.sourceforge.jeval.Evaluator;

/**
 * Singleton class containing global settings of the switco scheduling algorithm
 * @author vdusa
 */
public class DefaultConvexCostFunction extends ConvexCostFunction {
    private String costFunction;
    
    /**
     * Default constructor
     */
    public DefaultConvexCostFunction(){
    }

    /**
     * Constructor
     * 
     * @param costFunction see setCostFunction()
     */
    public DefaultConvexCostFunction(String costFunction){
        setCostFunction(costFunction);
    }

    /**
     * Cost function is evaluated by the JEval java Library. For more information
     * see http://jeval.sourceforge.net.
     *
     * The cost function MUST be a convex function! Otherwise the algorithm will
     * not work properly!
     *
     * The cost function must contain a variable 't', which denotes the time point.
     * The variable t must be introduced as #{t} in the function.
     * For example: setCostFunction("abs(2*#{t}-5)") denotes the function abs(2*t-5).
     * 
     * @param costFunction the costFunction to set
     */
    public final void setCostFunction(String costFunction) {
        this.costFunction = costFunction;
    }

    /**
     * @return the getCostFunction()
     */
    public String getCostFunction() {
        return costFunction;
    }
    
    /**
     * @return function as a string
     */
    @Override
    public String toString(){
        return getCostFunction();
    }

    /**
     * Evaluates the given cost function in the time point t.
     * 
     * @param t time point
     * @return value of the costFunction(t)
     */
    public Double evaluate(double t) throws cz.dusa.switco.EvaluationException {
        try {
            Evaluator evaluator = new Evaluator();
            Double timePoint = t + getTimeShift();
            evaluator.putVariable("t", timePoint.toString());            
            return new Double(evaluator.evaluate(getCostFunction()));
        } catch (net.sourceforge.jeval.EvaluationException ex) {
            throw new cz.dusa.switco.EvaluationException(ex.getMessage());
        }            
    }


}
